<script setup lang="ts">
import { getHomeGoodsGuessLikeAPI } from '@/services/home'
import type { PageParams } from '@/types/global'
import type { GuessItem } from '@/types/home'
import { ref, onMounted } from "vue"

// 猜你喜欢列表数据
const guessList = ref<GuessItem[]>([])
// 通用分页数据
const pageParams: Required<PageParams> = {
    page: 1,
    pageSize: 10
}
// 分页结束标记
const finish = ref(false)

// 获取猜你喜欢列表数据
const getHomeGoodsGuessLikeData = async () => {
    // 若页码为最大后, 则不请求数据, 退出判断(性能优化)
    if (finish.value === true) {
        return uni.showToast({ icon: 'none', title: '没有更多商品了~' })
    }
    // 请求猜你喜欢数据
    const res = await getHomeGoodsGuessLikeAPI(pageParams)
    guessList.value.push(...res.result.items) // 数组追加
    // 分页条件-页码累加
    if (pageParams.page < res.result.pages) {
        pageParams.page++
    } else {
        finish.value = true
    }
}

// 重置分页数据(用于下拉刷新)
const resetData = () => {
    pageParams.page = 1,
        guessList.value = [],
        finish.value = false
}

// 组件挂载后调用
onMounted(() => {
    getHomeGoodsGuessLikeData()
})

// 暴露方法
defineExpose({
    getMore: getHomeGoodsGuessLikeData,
    resetData
})
</script>

<template>
    <!-- 猜你喜欢 -->
    <view class="caption">
        <text class="text">猜你喜欢</text>
    </view>
    <view class="guess">
        <navigator class="guess-item" v-for="item in guessList" :key="item.id" :url="`/pages/goods/goods?id=${item.id}`">
            <image :src="item.picture" class="image" mode="aspectFill"></image>
            <view class="name"> {{ item.name }} </view>
            <view class="price">
                <text class="small">¥</text>
                <text>{{ item.price }}</text>
            </view>
        </navigator>
    </view>
    <view class="loading-text"> {{ finish ? '没有更多商品了~' : '正在加载...' }} </view>
</template>

<style lang="scss">
:host {
    display: block;
}
/* H5端默认开启scoped样式隔离, 导致组件基础样式无效 */
@import '@/components/styles/XtxGuess.scss';
</style>